package com.softserveinc.autorent.manager;

import java.util.List;

import javax.persistence.EntityManager;


public abstract class AbstractEJB<T> {

	private Class<T> entityClass;

	public Class<T> getEntityClass() {
		return entityClass;
	}

	public AbstractEJB(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	protected abstract EntityManager getEntityManager();

	protected abstract void setEntityManager(EntityManager em);

	public T  create(T entity) {
		if (entity != null) 
		   getEntityManager().persist(entity);
		   return entity;
		 }


	public T read(int id) {
		return getEntityManager().find(entityClass, id);
	}

	public T update(T entity) {
		if (entity != null) 
			getEntityManager().merge(entity);
		return entity;
	}

	public void delete(T entity) {
		if (entity != null) {
			getEntityManager().remove(entity);
		}
	}

	public void delete(int id) {
		T entity = (T) getEntityManager().find(entityClass, id);
		delete(entity);
	}

//	public Collection<T> getAll() {
//		final String className = entityClass.getSimpleName();
//		Query q = getEntityManager().createQuery("from " + className + " c");
//		Collection<T> lst = q.getResultList();
//		return lst;
//	}
	public abstract List<T> findAll();
}
